/**
 * 处理组件传递值F
 * @param {String} value
 */
function handleUnit(value, unit = 'rpx') {
	const reg = /^[0-9]*$/g;
	return typeof value === 'number' || reg.test(value) ? value + unit : value;
}

/**
 * 预览图片
 * @param {Array} urls
 * @param {Number} index
 */
function previewImages(urls, current = 0) {
	uni.previewImage({
		urls,
		current
	});
}

/**
 * 防抖函数
 * @param {Function} func
 * @param {Number} wait
 * @param {Boolean} immediate
 * @returns
 */
function debounce(func, wait = 300, immediate = true) {
	let timer = null;
	return function () {
		if (timer) clearTimeout(timer);
		if (immediate) {
			let exec = !timer;
			timer = setTimeout(() => {
				timer = null;
			}, wait);

			if (exec) {
				func.apply(null, arguments);
			}
		} else {
			timer = setTimeout(() => {
				func.apply(null, arguments);
			}, wait);
		}
	};
}

/**
 * 获取系统信息
 */
function getSystemInfo() {
	let info;
	try {
		info = uni.getSystemInfoSync();
		return info;
	} catch (e) {
		//TODO handle the exception
	}
}

/**
 * 获取日历信息
 * @param {Number} timestamp 时间戳精确到毫秒
 */
function getDateInfo(timestamp) {
	const date = timestamp ? new Date(timestamp) : new Date();
	const year = date.getFullYear();
	const month = date.getMonth() + 1;
	const day = date.getDate();
	return [year, month, day];
}

/**
 * 格式化日期对象
 * @param {Number} timestamp 时间戳精确到毫秒
 */

function formatDate(timestamp) {
	let [year, month, day] = getDateInfo(timestamp);
	month = month < 10 ? '0' + month : month;
	day = day < 10 ? '0' + day : day;
	return year + '-' + month + '-' + day;
}

export { handleUnit, previewImages, getSystemInfo, debounce, getDateInfo, formatDate };
